package com.woniu.controller;

import com.woniu.entity.AddGroup;
import com.woniu.entity.PageBean;
import com.woniu.entity.Role;
import com.woniu.entity.UpdateGroup;
import com.woniu.entity.response.ResponseEntity;
import com.woniu.entity.vo.RoleVO;
import com.woniu.service.IRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hyl
 * @since 2022-08-28
 */
@RestController
@RequestMapping("/brain/role")
@Validated
@Slf4j
public class RoleController {
    @Autowired
    private IRoleService roleService;
    /**
     * 提交添加角色请求，持久化数据
     *
     * @return 返回操作结果
     */
    @PostMapping(value = "/add")
    public ResponseEntity<String> roleAdd(@RequestBody @Validated({AddGroup.class, Default.class}) RoleVO roleVO) {

        Role role = roleVO.getRole();
        role.setRoleStatus("y");

        roleService.add(role, roleVO.getMenuIds(), roleVO.getAuthIds());

        return ResponseEntity.defaultRes(null,"添加成功","200");
    }

    @GetMapping("/isExists")
    public ResponseEntity<Integer> isExists(@NotEmpty(message = "name 不能为空") String name) {
        return ResponseEntity.success(roleService.getByName(name));
    }


    /**
     * 逻辑删除角色
     *
     * @param id 角色id
     * @return 返回操作结果，200 -> 删除成功，500 -> 操作失败
     * @throws Exception 数据库异常时，抛出该异常
     */
    @GetMapping("/delete")
    public ResponseEntity<String> delete(
            @NotNull(message = "id 不能为 null")
            @Min(value = 1, message = "id 最小为 1") Integer id) {

        roleService.delete(id);

        return ResponseEntity.defaultRes(null,"删除成功","200");
    }


    @PostMapping("/update")
    public ResponseEntity<String> update(@RequestBody @Validated({UpdateGroup.class, Default.class}) RoleVO roleVO) {

        Role role = roleVO.getRole();
        role.setRoleStatus("y");

        roleService.update(role, roleVO.getAuthIds(), roleVO.getMenuIds());

        return ResponseEntity.defaultRes(null,"修改成功","200");
    }


    @GetMapping("/list")
    public ResponseEntity<PageBean<Role>> roleList(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageBean<Role> pageBean;

        pageBean = roleService.getByPage(new Role(), pageNum, 10);

        return ResponseEntity.success(pageBean,"200");
    }

}
